{% extends "base.html" %}

{% block title %}设备管理{% endblock %}

{% block page_title %}设备管理{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.4.1/dist/MarkerCluster.Default.css">
<style>
.device-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
}

.device-list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
}

.device-card {
    background: white;
    border-radius: var(--border-radius);
    padding: 20px;
    box-shadow: var(--box-shadow);
}

.device-card h3 {
    color: var(--secondary-color);
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.device-status {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.8em;
}

.device-status.online {
    background: #e8f5e9;
    color: #2e7d32;
}

.device-status.offline {
    background: #ffebee;
    color: #c62828;
}

.device-info {
    margin-bottom: 15px;
}

.device-info p {
    margin: 8px 0;
    color: var(--text-color);
}

.device-actions {
    display: flex;
    gap: 10px;
}

.btn {
    padding: 8px 12px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.9em;
    transition: all 0.3s ease;
}

.btn-primary {
    background: var(--primary-color);
    color: white;
}

.btn-secondary {
    background: var(--secondary-color);
    color: white;
}

.btn-danger {
    background: #e74c3c;
    color: white;
}

.btn:hover {
    opacity: 0.9;
    transform: translateY(-1px);
}

#map {
    height: 400px;
    margin-top: 20px;
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
}

.modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    background: white;
    padding: 20px;
    border-radius: 8px;
    width: 100%;
    max-width: 500px;
}

.toast {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 15px 25px;
    border-radius: 4px;
    z-index: 1001;
}

.toast.error {
    background: #dc3545;
    color: white;
}

.toast-content {
    display: flex;
    align-items: center;
    gap: 10px;
}

.device-container {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
    margin: 20px;
}

.map-container {
    background: white;
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
    height: 500px;
    position: relative;
    overflow: hidden;
    margin-bottom: 20px;
    width: 100%;
}

#device-map {
    height: 100%;
    width: 100%;
}

.map-controls {
    position: absolute;
    top: 80px;
    right: 10px;
    z-index: 1000;
    background: white;
    padding: 10px;
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.device-marker-container {
    width: 30px !important;
    height: 30px !important;
    margin-left: -15px !important;
    margin-top: -15px !important;
}

.device-marker {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    background: white;
    padding: 5px;
    border-radius: 50%;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    width: 100%;
    height: 100%;
}

.device-marker i {
    font-size: 16px;
    margin-bottom: 2px;
}

.device-marker.online i {
    color: #28a745;
}

.device-marker.offline i {
    color: #dc3545;
}

.sim-status {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.8em;
    margin-top: 5px;
}

.sim-active {
    background: #d4edda;
    color: #155724;
}

.sim-expiring {
    background: #fff3cd;
    color: #856404;
}

.sim-expired {
    background: #f8d7da;
    color: #721c24;
}

.device-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin: 20px;
}

.stat-card {
    background: white;
    border-radius: 10px;
    padding: 20px;
    text-align: center;
    box-shadow: var(--box-shadow);
}

.stat-value {
    font-size: 2em;
    font-weight: bold;
    color: var(--primary-color);
    margin-bottom: 10px;
}

.stat-card.warning .stat-value {
    color: #f1c40f;
}

.stat-card.danger .stat-value {
    color: #e74c3c;
}

.map-legend {
    position: absolute;
    bottom: 20px;
    left: 20px;
    background: white;
    padding: 10px;
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    z-index: 1000;
}

.legend-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 5px 0;
}

.status-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
}

.status-dot.online {
    background: #28a745;
}

.status-dot.offline {
    background: #dc3545;
}

.map-toolbar {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 1000;
    background: white;
    padding: 10px;
    border-radius: 4px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    display: flex;
    gap: 10px;
}

.toolbar-group {
    display: flex;
    gap: 5px;
}

.device-popup {
    min-width: 250px;
}

.device-popup h3 {
    margin-bottom: 10px;
    padding-bottom: 5px;
    border-bottom: 1px solid #eee;
}

.device-popup p {
    margin: 5px 0;
    display: flex;
    align-items: center;
    gap: 5px;
}

.popup-actions {
    display: flex;
    gap: 5px;
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #eee;
}

.location-inputs {
    display: grid;
    grid-template-columns: 1fr 1fr auto;
    gap: 10px;
    align-items: center;
}

.device-cluster {
    background: white;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

.device-name {
    background: rgba(255, 255, 255, 0.9);
    padding: 2px 5px;
    border-radius: 3px;
    font-size: 0.8em;
    margin-top: 2px;
}

/* 农田样式 */
.field-polygon {
    stroke: #3388ff;
    stroke-width: 2;
    fill-opacity: 0.1;
    fill: #3388ff;
}

.field-polygon:hover {
    fill-opacity: 0.2;
}
</style>
{% endblock %}

{% block content %}
<div class="device-stats">
    <div class="stat-card">
        <div class="stat-value">{{ stats.total }}</div>
        <div class="stat-label">总设备数</div>
    </div>
    <div class="stat-card">
        <div class="stat-value">{{ stats.online }}</div>
        <div class="stat-label">在线设备</div>
    </div>
    <div class="stat-card">
        <div class="stat-value">{{ stats.offline }}</div>
        <div class="stat-label">离线设备</div>
    </div>
    <div class="stat-card warning">
        <div class="stat-value">{{ stats.sim_expiring }}</div>
        <div class="stat-label">物联网卡即将到期</div>
    </div>
    <div class="stat-card danger">
        <div class="stat-value">{{ stats.sim_expired }}</div>
        <div class="stat-label">物联网卡已过期</div>
    </div>
</div>

<div class="device-container">
    <div class="map-container">
        <div id="device-map"></div>
        <div class="map-toolbar">
            <div class="toolbar-group">
                <select id="device-type-filter" onchange="filterDevices()">
                    <option value="all">所有类型</option>
                    <option value="soil_moisture">土壤墒情</option>
                    <option value="irrigation">灌溉设备</option>
                    <option value="weather">气象站</option>
                </select>
                <select id="device-status-filter" onchange="filterDevices()">
                    <option value="all">所有状态</option>
                    <option value="online">在线</option>
                    <option value="offline">离线</option>
                </select>
            </div>
            <div class="toolbar-group">
                <button class="btn btn-primary" onclick="refreshDeviceStatus()">
                    <i class="fas fa-sync-alt"></i> 刷新状态
                </button>
            </div>
        </div>
        <div class="map-legend">
            <div class="legend-item">
                <i class="fas fa-tint"></i> 土壤墒情
            </div>
            <div class="legend-item">
                <i class="fas fa-shower"></i> 灌溉设备
            </div>
            <div class="legend-item">
                <i class="fas fa-cloud-sun"></i> 气象站
            </div>
            <div class="legend-item">
                <span class="status-dot online"></span> 在线
            </div>
            <div class="legend-item">
                <span class="status-dot offline"></span> 离线
            </div>
        </div>
    </div>

    <div class="device-header">
        <h2>设备列表</h2>
        <button class="btn btn-primary" onclick="showAddDeviceModal()">
            <i class="fas fa-plus"></i> 添加设备
        </button>
    </div>

    <div class="device-list">
        {% for device in devices %}
        <div class="device-card" data-device-type="{{ device.device_type }}" data-device-id="{{ device.id }}">
            <h3>
                {{ device.name }}
                <span class="device-status {{ 'online' if device.is_online else 'offline' }}">
                    {{ '在线' if device.is_online else '离线' }}
                </span>
            </h3>
            <div class="device-info">
                <p><i class="fas fa-microchip"></i> 类型: {{ device.device_type }}</p>
                <p><i class="fas fa-map-marker-alt"></i> 农田: {{ fields[device.field_id].name }}</p>
                {% if device.sim_expire_date %}
                <p>
                    <i class="fas fa-sim-card"></i> 物联网卡:
                    <span class="sim-status sim-{{ device.sim_status }}">
                        {% if device.sim_status == 'active' %}
                            有效期至 {{ device.sim_expire_date|datetime }}
                        {% elif device.sim_status == 'expiring' %}
                            即将到期 ({{ device.sim_expire_date|datetime }})
                        {% else %}
                            已过期 ({{ device.sim_expire_date|datetime }})
                        {% endif %}
                    </span>
                </p>
                {% endif %}
            </div>
            <div class="device-actions">
                <button class="btn btn-primary" onclick="viewDeviceData({{ device.id }})">
                    <i class="fas fa-chart-line"></i> 查看数据
                </button>
                <button class="btn btn-secondary" onclick="editDevice({{ device.id }})">
                    <i class="fas fa-edit"></i> 编辑
                </button>
                <button class="btn btn-danger" onclick="deleteDevice({{ device.id }})">
                    <i class="fas fa-trash"></i> 删除
                </button>
            </div>
        </div>
        {% endfor %}
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet.markercluster@1.4.1/dist/leaflet.markercluster.js"></script>
<script>
let map;
let markers = {};
let markerClusterGroup;
const deviceTypeIcons = {
    'soil_moisture': 'fa-tint',
    'irrigation': 'fa-shower',
    'weather': 'fa-cloud-sun'
};

// 初始化地图
function initMap() {
    // 确保地图容器存在
    const mapContainer = document.getElementById('device-map');
    if (!mapContainer) {
        console.error('地图容器不存在');
        return;
    }
    
    // 创建地图实例
    map = L.map('device-map', {
        center: [43.825, 87.6],  // 新疆农业大学位置
        zoom: 15,
        minZoom: 3,
        maxZoom: 18,
        zoomControl: false  // 禁用默认缩放控件
    });
    
    // 添加高德地图底图
    L.tileLayer('http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {
        subdomains: ["1", "2", "3", "4"],
        maxZoom: 18
    }).addTo(map);
    
    // 添加自定义缩放控件
    L.control.zoom({
        position: 'topright'
    }).addTo(map);
    
    // 获取所有农田边界的边界框
    let bounds = null;
    let currentBounds;
    {% for field in fields.values() %}
    {% if field.boundary %}
        currentBounds = L.latLngBounds({{ field.boundary|tojson|safe }});
        if (!bounds) {
            bounds = currentBounds;
        } else {
            bounds.extend(currentBounds);
        }
    {% endif %}
    {% endfor %}
    
    // 初始化标记聚合组
    markerClusterGroup = L.markerClusterGroup({
        iconCreateFunction: function(cluster) {
            const count = cluster.getChildCount();
            return L.divIcon({
                html: `<div class="device-cluster">${count}</div>`,
                className: 'device-cluster-icon'
            });
        },
        maxClusterRadius: 50,
        spiderfyOnMaxZoom: true,
        showCoverageOnHover: true,
        zoomToBoundsOnClick: true
    });
    map.addLayer(markerClusterGroup);
    
    // 添加农田边界
    {% for field in fields.values() %}
    {% if field.boundary %}
    L.polygon({{ field.boundary|tojson|safe }}, {
        color: '#3388ff',
        weight: 2,
        fillOpacity: 0.1,
        className: 'field-polygon'
    }, {
        closeButton: false,
        closeOnClick: false
    }).addTo(map);
    {% endif %}
    {% endfor %}
    
    // 如果有边界，调整地图视图
    if (bounds) {
        map.fitBounds(bounds, {
            padding: [100, 100]  // 增加边距
        });
    }
    
    // 添加设备标记
    {% for device in devices %}
    {% if device.location %}
    addDeviceMarker({{ device|tojson|safe }});
    {% endif %}
    {% endfor %}
    
    // 强制重新计算地图大小
    map.invalidateSize();
}

// 页面加载完成后初始化地图
window.addEventListener('load', initMap);

// 刷新设备状态
async function refreshDeviceStatus() {
    try {
        const response = await fetch('/api/devices/status');
        if (!response.ok) {
            throw new Error('获取设备状态失败');
        }
        
        const devices = await response.json();
        
        // 更新设备卡片状态
        devices.forEach(device => {
            const card = document.querySelector(`.device-card[data-device-id="${device.id}"]`);
            if (card) {
                // 更新状态标签
                const statusSpan = card.querySelector('.device-status');
                if (statusSpan) {
                    statusSpan.className = `device-status ${device.is_online ? 'online' : 'offline'}`;
                    statusSpan.textContent = device.is_online ? '在线' : '离线';
                }
                
                // 更新物联网卡状态（如果有）
                if (device.sim_status) {
                    const simStatus = card.querySelector('.sim-status');
                    if (simStatus) {
                        simStatus.className = `sim-status sim-${device.sim_status}`;
                        let statusText = '';
                        if (device.sim_status === 'active') {
                            statusText = `有效期至 ${formatDate(device.sim_expire_date)}`;
                        } else if (device.sim_status === 'expiring') {
                            statusText = `即将到期 (${formatDate(device.sim_expire_date)})`;
                        } else {
                            statusText = `已过期 (${formatDate(device.sim_expire_date)})`;
                        }
                        simStatus.textContent = statusText;
                    }
                }
            }
            
            // 更新地图标记
            const marker = markers[device.id];
            if (marker) {
                const icon = deviceTypeIcons[device.device_type] || 'fa-microchip';
                const status = device.is_online ? 'online' : 'offline';
                const markerHtml = `
                    <div class="device-marker ${status}">
                        <i class="fas ${icon}"></i>
                        <div class="device-name">${device.name}</div>
                    </div>
                `;
                
                marker.marker.setIcon(L.divIcon({
                    html: markerHtml,
                    className: 'device-marker-container',
                    iconSize: null
                }));
            }
        });
        
        // 显示成功提示
        showToast('设备状态已更新', 'success');
    } catch (error) {
        console.error('刷新设备状态失败:', error);
        showToast('刷新设备状态失败', 'error');
    }
}

// 显示提示信息
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `
        <div class="toast-content">
            <i class="fas ${type === 'error' ? 'fa-exclamation-circle' : 'fa-check-circle'}"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(toast);
    
    // 3秒后自动移除
    setTimeout(() => {
        toast.remove();
    }, 3000);
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
}

// 添加设备标记
function addDeviceMarker(device) {
    // 检查设备位置是否有效
    if (!device.location || typeof device.location.lat !== 'number' || typeof device.location.lng !== 'number') {
        console.error('设备位置无效:', device);
        return;
    }
    
    const icon = deviceTypeIcons[device.device_type] || 'fa-microchip';
    const status = device.is_online ? 'online' : 'offline';
    
    const markerHtml = `
        <div class="device-marker ${status}">
            <i class="fas ${icon}"></i>
            <div class="device-name">${device.name}</div>
        </div>
    `;
    
    const marker = L.marker([device.location.lat, device.location.lng], {
        icon: L.divIcon({
            html: markerHtml,
            className: 'device-marker-container',
            iconSize: null  // 让CSS控制大小
        })
    });
    
    // 只添加到聚合组
    if (markerClusterGroup) {
        markerClusterGroup.addLayer(marker);
    }
}
</script>
{% endblock %}